import Vue from "vue";
import Router from "vue-router";
import admin from "./admin";
import { getToken } from "@/utils/auth";

/* 解决 vue router 网页报错问题 */
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
Vue.use(Router);
export const routes = [
  /* 首页，不要用 () => import() */
  {
    alias: "/",
    path: "/home",
    component: () => import(/* webpackChunkName: "home" */ "../views/Home.vue"),
    meta: {
      title: "博客，记录美好生活"
    },
    hidden: true
  },
  {
    path: "/image",
    component: () => import("../views/image/index.vue"),
    meta: {
      title: "相册"
    }
  },
  {
    path: "/image/detail",
    component: () => import("../views/image/ImageDetail.vue"),
    meta: {
      title: "图片详情"
    },
    hidden: true
  },
  {
    path: "/detail",
    component: () => import("../views/article/detail.vue"),
    meta: {
      title: "博客详情"
    },
    hidden: true
  },
  {
    path: "/blogroll",
    component: () =>
      import(/* webpackChunkName: "blogroll" */ "../views/blogroll/index.vue"),
    meta: {
      title: "云圈"
    }
  },
  {
    path: "/guestbook",
    component: () => import("../views/guestbook/index.vue"),
    meta: {
      title: "留言板"
    }
  },
  {
    path: "/",
    meta: {
      title: "其他"
    },
    component: () => import("../views/RouterView.vue"),
    children: [
      {
        path: "/aboutme",
        component: () => import("../views/other/about/index.vue"),
        meta: {
          title: "关于我"
        }
      },
      {
        path: "/version",
        component: () => import("../views/other/version/index.vue"),
        meta: {
          title: "时光机"
        }
      }
    ]
  }
];

export function createRouter() {
  const router = new Router({
    mode: "history",
    routes: [
      /* 客户端路由 */
      {
        path: "/",
        component: () => import("../views/layout/index.vue"),
        redirect: "/home",
        meta: {
          title: "首页"
        },
        children: routes
      },
      {
        path: "/login",
        component: () => import("../views/login/index.vue")
      },
      admin
    ]
  });
  // 用户权限校验
  if (!Vue.prototype.$isServer) {
    router.beforeEach((to, from, next) => {
      const toPath = to.path;
      const isAdminPath = toPath.includes("/admin");
      const isLoginPath = toPath === "/login";
      const token = getToken();
      if (token) {
        // 已经登录
        if (isLoginPath) {
          return next({ path: "/admin" });
        }
      } else {
        // 未登录
        if (isAdminPath) {
          return next({ path: "/login" });
        }
      }
      next();
    });
  }
  return router;
}
